package com.aletto.demo_android_web3j.utils;

import android.content.Context;
import android.util.Log;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.HDPath;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bouncycastle.util.encoders.Hex;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.Wallet;
import org.web3j.crypto.WalletFile;
import org.web3j.protocol.ObjectMapperFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthEstimateGas;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.utils.Numeric;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;
import org.web3j.crypto.Bip32ECKeyPair;


import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Nonnull;


public class UtilWeb3J {

    public static void test() {

    }

    /**
     * 根据助记词加载钱包
     *
     * @param passphrase 密码
     * @param mnemonic   助记词
     */
    public static Credentials importWalletByMnemonic(String passphrase, String mnemonic) {
        try {

            // 检查格式
            MnemonicCode mc = new MnemonicCode();
            List<String> words = Arrays.asList(mnemonic.split(" "));
            mc.check(words);

            // 导出助记词
            byte[] seed = MnemonicCode.toSeed(Arrays.asList(mnemonic.split(" ")), passphrase);
            Bip32ECKeyPair masterKeypair = Bip32ECKeyPair.generateKeyPair(seed);

            Bip32ECKeyPair childKeypair = Bip32ECKeyPair.deriveKeyPair(
                    masterKeypair,
                    Arrays.stream("/44/60/0/0/0".split("/"))
                            .filter(s -> !s.isEmpty())
                            .map(s -> s.startsWith("'") ? Integer.parseInt(s.substring(1)) : Integer.parseInt(s))
                            .collect(Collectors.toList())
                            .stream()
                            .mapToInt(Integer::intValue)
                            .toArray()
            );

            Credentials credentials = Credentials.create(childKeypair);
            String address = credentials.getAddress();
            ECKeyPair ecKeyPair = credentials.getEcKeyPair();

            Log.d("WEB3J:Utils", address);
            Log.d("WEB3J:Utils", Numeric.toHexString(ecKeyPair.getPublicKey().toByteArray()));
            Log.d("WEB3J:Utils", Numeric.toHexString(ecKeyPair.getPrivateKey().toByteArray()));

            return credentials;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据私钥加载钱包
     *
     * @param inputPrivateKey 私钥
     */
    public static Credentials importWalletByPrivateKey(String inputPrivateKey) {
        Credentials credentials = Credentials.create(inputPrivateKey);
        String address = credentials.getAddress();
        ECKeyPair ecKeyPair = credentials.getEcKeyPair();

        Log.d("WEB3J:Utils", address);
        Log.d("WEB3J:Utils", Numeric.toHexString(ecKeyPair.getPublicKey().toByteArray()));
        Log.d("WEB3J:Utils", Numeric.toHexString(ecKeyPair.getPrivateKey().toByteArray()));
        return credentials;
    }

}
